<template>
  <div class="tc-player-container" ref="containerRef">
    <!-- TCPlayer将在这里渲染 -->
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, onUnmounted, watch, nextTick } from 'vue'
import TCPlayer from 'tcplayer.js'
import 'tcplayer.js/dist/tcplayer.min.css'

// 组件属性定义
const props = defineProps({
  // 视频源URL
  src: {
    type: String,
    required: true
  },
  // 是否自动播放
  autoplay: {
    type: Boolean,
    default: false
  },
  // 播放器宽度
  width: {
    type: String,
    default: '100%'
  },
  // 播放器高度
  height: {
    type: String,
    default: '100%'
  },
  // 许可证URL（如果需要）
  licenseUrl: {
    type: String,
    default: ''
  },
  // HLS配置
  hlsConfig: {
    type: Object,
    default: () => ({
      debug: false, // 关闭调试日志
			enableWorker: true, // 启用多线程解码
			maxBufferLength: 10, // 最大缓冲时长（秒）
			maxMaxBufferLength: 30, // 最大最大缓冲时长（秒）
			maxBufferSize: 40 * 1024 * 1024, // 最大缓冲大小（字节）
    })
  },
  bigPlayButton: {
    type: Boolean,
    default: true
  }
})

// 组件事件
const emit = defineEmits([
  'play',       // 播放事件
  'pause',      // 暂停事件
  'ended',      // 播放结束事件
  'error',      // 错误事件
  'ready'       // 播放器准备就绪事件
])

// DOM引用
const containerRef = ref<HTMLDivElement | null>(null)
let videoElement: HTMLVideoElement | null = null
let playerInstance: any = null
let playerId = `tcplayer_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`

// 创建播放器实例
const createPlayer = async () => {
  if (!containerRef.value || !props.src) return
  
  // 销毁已存在的播放器实例
  if (playerInstance) {
    playerInstance.dispose()
  }
  
  // 清空容器
  containerRef.value.innerHTML = ''
  
  // 创建视频元素
  videoElement = document.createElement('video')
  videoElement.id = playerId
  videoElement.preload = 'meta'
  videoElement.playsInline = true
  videoElement.setAttribute('webkit-playsinline', 'true')
  
  // 添加到容器
  containerRef.value.appendChild(videoElement)
  
  // 检测视频格式
  const isM3u8 = props.src.toLowerCase().includes('.m3u8')
  
  // 初始化TCPlayer
  playerInstance = TCPlayer(playerId, {
    hlsConfig: props.hlsConfig,
    sources: [
      {
        src: props.src,
        type: isM3u8 ? 'application/x-mpegURL' : 'video/mp4'
      }
    ],
    preload: props.bigPlayButton ? 'meta' : 'none',
    autoplay: props.autoplay,
    bigPlayButton: props.bigPlayButton,
    posterImage: true,
    poster: '',
    controls: props.bigPlayButton,
    controlBar: {
      playToggle: true,
      progressControl: true,
      volumePanel: true,
      currentTimeDisplay: true,
      durationDisplay: true,
      timeDivider: true,
      playbackRateMenuButton: true,
      fullscreenToggle: true,
      QualitySwitcherMenuButton: false
    },
    // 关键配置：禁用错误弹窗以避免aria-hidden问题
    errorTips: false,
    errorLog: false,
    // 许可证URL（如果提供）
    licenseUrl: props.licenseUrl
  })
  
  // 注册事件监听
  playerInstance.on('play', () => emit('play'))
  playerInstance.on('pause', () => emit('pause'))
  playerInstance.on('ended', () => emit('ended'))
  playerInstance.on('error', (e: any) => {
    console.error('TCPlayer播放错误:', e)
    emit('error', e)
  })

  if (!props.bigPlayButton) {
    playerInstance.controlBar.hide();
    // 禁用点击播放
    playerInstance.off('click');
  }
  
  // 播放器就绪
  emit('ready', playerInstance)
}

// 监听视频源变化
watch(() => props.src, () => {
  if (containerRef.value) {
    nextTick(() => {
      createPlayer()
    })
  }
})

// 监听自动播放状态变化
watch(() => props.autoplay, (newVal) => {
  if (playerInstance) {
    if (newVal) {
      playerInstance.play()
    } else {
      playerInstance.pause()
    }
  }
})

// 组件挂载时创建播放器
onMounted(() => {
  if (containerRef.value && props.src) {
    nextTick(() => {
      createPlayer()
    })
  }
})

// 组件卸载时清理资源
onUnmounted(() => {
  if (playerInstance) {
    playerInstance.dispose()
    playerInstance = null
  }
  videoElement = null
})

// 暴露方法给父组件
defineExpose({
  // 播放视频
  play: () => {
    if (playerInstance) playerInstance.play()
  },
  // 暂停视频
  pause: () => {
    if (playerInstance) playerInstance.pause()
  },
  // 跳转指定时间
  seek: (time: number) => {
    if (playerInstance) playerInstance.currentTime(time)
  },
  // 获取当前播放时间
  getCurrentTime: () => {
    return playerInstance ? playerInstance.currentTime() : 0
  },
  // 获取实例（谨慎使用）
  getInstance: () => playerInstance
})
</script>

<style lang="scss" scoped>
.tc-player-container {
  position: relative;
  width: v-bind('props.width');
  height: v-bind('props.height');
  background-color: #000;
  overflow: hidden;

  :deep(.tcplayer) {
    width: 100% !important;
    height: 100% !important;
  }
  
  // 确保TCPlayer创建的div充满容器
  :deep(.vjs-tech) {
    width: 100% !important;
    height: 100% !important;
  }
  
  // 彻底解决aria-hidden问题的样式
  :deep(.vjs-error-display) {
    display: none !important;
    visibility: hidden !important;
    opacity: 0 !important;
    pointer-events: none !important;
  }
  
  :deep(.vjs-modal-dialog) {
    display: none !important;
    visibility: hidden !important;
    opacity: 0 !important;
    pointer-events: none !important;
  }
  
  :deep([aria-hidden="true"]) {
    pointer-events: none !important;
  }
}
</style>